package com.yuanfeng.authserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.yuanfeng.authserver.entity.LoginUser;
import com.yuanfeng.authserver.feign.UserServiceClient;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author hyq
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserServiceClient userServiceClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        UserInfoVO userInfoVO=new UserInfoVO();
        userInfoVO.setUserMobile(username);
        userInfoVO.setLoginType(CommonType.commonStatus.NO.getCode());
        ResponseResult  userInfo = userServiceClient.querUserInfoByParams(userInfoVO);

       //根据用户名查询用户信息(后台系统)
       Map<String, String> map=new HashMap<>();
       map.put("userAccount",username);
       ResponseResult adminData=userServiceClient.getPlatformUserInfo(map);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(userInfo.getData()) && Objects.isNull(adminData.getData())){
            throw new RuntimeException(BizCodeEnume.USER_DOES_NOT_EXIST.getMsg());
        }

        if(!Objects.isNull(adminData.getData())){
            //TODO 根据用户查询权限信息 添加到LoginUser中
            UserInfoVO adminUser = JSON.parseObject(JSON.toJSONString(adminData.getData()), UserInfoVO.class);
            List<String> list =Arrays.asList(adminUser.getRightsLimitsAll().split(","));

            //封装成UserDetails对象返回
            return new LoginUser(adminUser,list);
        }
        UserInfoVO user = JSON.parseObject(JSON.toJSONString(userInfo.getData()), UserInfoVO.class);
        return new LoginUser(user,null);
    }
}

